import axios from 'axios'
import Qs from 'Qs';
import Store from '../store/index'
import router from '../router'
import {
	Dialog
} from 'we-vue'
import {
	Toast
} from 'we-vue'

//设置环境变量 确认默认请求地址
if (process.env.NODE_ENV == 'development') {
	axios.defaults.baseURL = 'http://192.168.80.9/HSG_OA/'
	// axios.defaults.imgBaseUrl = 'http://59.175.233.138/img/';
} else if (process.env.NODE_ENV == 'debug') {
	axios.defaults.baseURL = 'https://oa.hsg.com.cn/'
	// axios.defaults.imgBaseUrl = 'http://img.hsg.com.cn/';
} else if (process.env.NODE_ENV == 'production') {
	axios.defaults.baseURL = 'https://pms.hsg.com.cn/'
	// axios.defaults.imgBaseUrl = 'http://img.hsg.com.cn/';
}

axios.defaults.timeout = 10000;
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';

//请求拦截器   接口发送请求前做些什么
axios.interceptors.request.use(
	config => {
		Toast.loading('loading...')
		return config;
	},
	error => {
		Toast.close()
		return Promise.error(error);
	}
)
//响应拦截器  接口返回后做些什么
axios.interceptors.response.use(
	response => {
		Toast.close()
		if (response.status === 200) {

			return Promise.resolve(response)
		} else {
			return Promise.reject(response);
		}
	},
	//服务器状态码不是200
	error => {
		Toast.close()
		if (error.response.status) {
			switch (error.response.status) {
				//未登录
				//跳转到登陆页面
				case 401:
					alert('页面错误')
					break;
				case 403:
					alert('token过期');
					break;
				default:
					alert('错误')
			}
			return Promise.reject(error.response);
		}
	}
)


/**
 * 配置图片默认地址
 */

export const imgBaseUrl = "http://192.168.80.9/img/"


/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */

export function get(url, params) {
	return new Promise((resolve, reject) => {
		axios.get(url, {
				params: params,
			})
			.then(res => {
				resolve(res.data);
			})
			.catch(err => {
				reject(err.data)
			})
	})
}


/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */

export function post(url, params) {
	params = Qs.stringify(params);
	return new Promise((resolve, reject) => {
		axios.post(url, params)
			.then(res => {
				resolve(res.data)
			})
			.catch(err => {
				reject(err.data)
			})
	})
}


/**
 * formData类型的请求方式
 */

export function formData(url, params) {
	return new Promise((resolve, reject) => {
			axios({
					method: 'post',
					url: url,
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded'
					},
					processData: false,
					data: params
				}).then(res => {
					resolve(res.data)
				})
				.catch(err => {
					reject(err.data)
				})
		})
	}
